import 'package:fluent_ui/fluent_ui.dart';

import '../../api/semester_api.dart';
import '../../components/data_table.dart';
import '../../model/semester_model.dart';
import '../../utils/date_utils.dart';
import '../../utils/loading_utils.dart';
import '../app/app_dict_data.dart';

abstract class SemesterField {}

//学年学期-查询字段
enum SemesterQueryField implements SemesterField {
  now('当前日期'),
  title('标题'),
  status("状态");

  final String label;

  const SemesterQueryField(this.label);
}

//学年学期-输入字段
enum SemesterInputField implements SemesterField {
  code('编码', checked: true),
  title('标题', checked: true),
  remark('备注'),
  start('开始日期', checked: true),
  end('结束日期', checked: true),
  isDef('是否默认'),
  status("状态", isAdd: false);

  final String label;
  final bool checked, isAdd;

  const SemesterInputField(
    this.label, {
    this.checked = false,
    this.isAdd = true,
  });

  String? validHandler(final String? val) {
    if (checked && (val == null || val.isEmpty)) {
      return '$label不能为空';
    }
    return null;
  }
}

///学年学期-视图模型
class SemesterViewModel extends ChangeNotifier {
  //查询字段
  final _queryFields = <SemesterQueryField, TextEditingController>{
    for (var field in SemesterQueryField.values) field: TextEditingController()
  };

  //输入字段
  final _inputFields = <SemesterInputField, TextEditingController>{
    for (var field in SemesterInputField.values) field: TextEditingController()
  };

  ///获取控制器
  TextEditingController? getController<T extends SemesterField>(final T field) {
    //查询字段
    if (field is SemesterQueryField) {
      return _queryFields[field];
    }
    //输入字段
    if (field is SemesterInputField) {
      return _inputFields[field];
    }
    return null;
  }

  ///获取字段值
  String? getFieldValue<T extends SemesterField>(final T field) {
    final ctr = getController(field);
    if (ctr != null) {
      return ctr.text;
    }
    return null;
  }

  ///设置字段值
  void setFieldValue<T extends SemesterField>(T field, String? val) {
    final controller = getController(field);
    if (controller != null) {
      controller.text = val ?? '';
    }
  }

  final _statusOpts = <ComboBoxItem<String>>[];

  ///获取状态选项集合
  List<ComboBoxItem<String>> get statusOpts => _statusOpts;

  ///加载字典
  void _loadDict(final List<Future<dynamic>> futures) {
    //状态
    if (_statusOpts.isEmpty) {
      final future = appDictData.buildOpts('status').then(
        (opts) {
          if (opts.isNotEmpty) {
            _statusOpts.addAll(opts);
          }
        },
      );
      futures.add(future);
    }
  }

  ///加载初始化
  void loadInit({final VoidCallback? afterHandler}) async {
    final futures = <Future<dynamic>>[];
    //加载字典
    _loadDict(futures);
    //请求等待
    if (futures.isNotEmpty) {
      await Future.wait(futures);
      notifyListeners();
    }
    //回调处理
    if (afterHandler != null) {
      afterHandler.call();
    }
  }

  //清空查询字段
  void cleanQueryFields() {
    for (var controller in _queryFields.values) {
      controller.clear();
    }
  }

  ///清空输入字端
  void cleanInputFields() {
    for (var controller in _inputFields.values) {
      controller.clear();
    }
  }

  ///分页查询模型
  final queryModel = PageModel<SemesterItemRes>();

  ///分页查询
  void query() async {
    try {
      loading.showLoading();
      final status = getFieldValue(SemesterQueryField.status);
      final now = getFieldValue(SemesterQueryField.now);
      final req = SemesterQueryReq(
        title: getFieldValue(SemesterQueryField.title) ?? '',
        now: dateUtils.parse('yyyy-MM-dd', now),
        status: int.tryParse(status ?? '') ?? -1,
        index: queryModel.current,
        size: queryModel.size,
      );
      final res = await semesterApi.query(req);
      if (res.isSuccessed) {
        queryModel.buildResData(res);
      }
      debugPrint('semesterApi.query(req:${req.toMap()})=>$res');
    } finally {
      loading.dismiss();
    }
  }

  ///加载数据
  void getInfoById(final String id) async {
    try {
      loading.showLoading();
      //加载数据
      final res = await semesterApi.info(id);
      if (res.isSuccessed) {
        //编码
        setFieldValue(SemesterInputField.code, res.code);
        //标题
        setFieldValue(SemesterInputField.title, res.title);
        //备注
        setFieldValue(SemesterInputField.remark, res.remark);
        //开始日期
        final String start = dateUtils.format('yyyy-MM-dd', res.start);
        setFieldValue(SemesterInputField.start, start);
        //结束日期
        final String end = dateUtils.format('yyyy-MM-dd', res.end);
        setFieldValue(SemesterInputField.end, end);
        //是否默认
        final String def = '${res.isDefault}';
        setFieldValue(SemesterInputField.isDef, def);
        //状态
        final String status = '${res.status}';
        setFieldValue(SemesterInputField.status, status);
        //触发通知
        notifyListeners();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }

  ///新增处理
  void onAddHandler(final VoidCallback handler) async {
    try {
      loading.showLoading();
      final start = getFieldValue(SemesterInputField.start);
      final end = getFieldValue(SemesterInputField.end);
      final isDef = getFieldValue(SemesterInputField.isDef);
      final req = SemesterAddReq(
        code: getFieldValue(SemesterInputField.code) ?? '',
        title: getFieldValue(SemesterInputField.title) ?? '',
        remark: getFieldValue(SemesterInputField.remark) ?? '',
        start: dateUtils.parse('yyyy-MM-dd', start),
        end: dateUtils.parse('yyyy-MM-dd', end),
        isDefault: int.tryParse(isDef ?? '') ?? 1,
      );
      //提交
      final res = await semesterApi.add(req);
      if (res.isSuccessed) {
        cleanInputFields();
        handler.call();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }

  ///修改处理
  void onModifyHandler(final String id, final VoidCallback handler) async {
    try {
      loading.showLoading();
      final start = getFieldValue(SemesterInputField.start);
      final end = getFieldValue(SemesterInputField.end);
      final isDef = getFieldValue(SemesterInputField.isDef);
      final status = getFieldValue(SemesterInputField.status);
      final req = SemesterModifyReq(
        id: id,
        code: getFieldValue(SemesterInputField.code) ?? '',
        title: getFieldValue(SemesterInputField.title) ?? '',
        remark: getFieldValue(SemesterInputField.remark) ?? '',
        start: dateUtils.parse('yyyy-MM-dd', start),
        end: dateUtils.parse('yyyy-MM-dd', end),
        isDefault: int.tryParse(isDef ?? '') ?? 0,
        status: int.tryParse(status ?? '') ?? 1,
      );
      //提交
      final res = await semesterApi.modify(req);
      if (res.isSuccessed) {
        cleanInputFields();
        handler.call();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }

  ///删除处理
  void onDeleteHandler(final String id) async {
    try {
      loading.showLoading();
      //删除处理
      final res = await semesterApi.delete(id);
      if (res.isSuccessed) {
        //重新加载数据
        query();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }
}
